<?php

namespace Core\Common\Base;

use Core\Common\Helper\HttpClient;
use GuzzleHttp\Client;

/**
 * Description of Consul
 *
 * @author baiyang@ibantang.com
 */
class Consul
{
    private static $instance = null;
    private $consul = null;

    private function __construct()
    {
        $config = ConsulConfig::newDefaultConfig();
        if (defined('CORE_CONSUL_AGENT')) {
            $config->setAddress(CORE_CONSUL_AGENT);
        }
        $this->consul = new \DCarbone\PHPConsulAPI\Consul($config);
    }

    private function getAgentAddr()
    {
        if (defined('CORE_CONSUL_AGENT')) {
            return CORE_CONSUL_AGENT;
        }
        return '127.0.0.1:8500';
    }

    /**
     * @return \self
     */
    public static function getInstance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function KV()
    {
        return $this->consul->KV();
    }

    public function Catalog()
    {
        return $this->consul->Catalog();
    }

    public function Health()
    {
        return $this->consul->Health();
    }

    public function getService($service, $protocol = 'http')
    {
        $catalog = $this->consul->Catalog();
        $data = $catalog->service($service);
        if (!$data) {
            return [];
        }
        $ret = [];
        foreach ($data[0] as $info) {
            if ('http' == $protocol) {
                $ret[] = [$info->ServiceAddress, $info->ServicePort];
            } elseif ('redis' == $protocol && isset($info->ServiceMeta['redis'])) {
                $ret[] = [$info->ServiceAddress, $info->ServiceMeta['redis']];
            }
        }
        return $ret;
    }

    public function registerService($baseInfo)
    {
        return HttpClient::put($this->getAgentAddr(), 'v1/agent/service/register', $baseInfo);
    }
}
